<template>
  <div class="carbon-price-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="180px">
      <template v-for="(item, index) in formList">
        <el-form-item
          v-if="!popConfig.disabled || item.prop !== 'sceneInfo' && popConfig.disabled"
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass">
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            :props="item.props"
            :options="item.options"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)">
            <template v-for="option in item.optionList" v-if="item.componentType === 'el-select'">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
            <template v-for="option in item.optionList" v-if="item.componentType === 'el-radio-group'">
              <el-radio :label="option.value">{{ option.label }}</el-radio>
            </template>
          </component>
        </el-form-item>
      </template>
      <el-form-item>
        [自动生成]：选择时间自动生成数据。当选择一天生成一条数据；当选择一个时间段生成多条的每日数据
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import { parseAareToObj, parseSceneData } from '@/utils/scene-data'
import api from '@/api/apis/sceneRoom'

export default {
  name: 'AddCarbonPrice',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      pickMinDate: '',
      formData: {},
      formList: [
        {
          name: '所属项目',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          attrConfig: {
            style: { width: '100%' },
            placeholder: '请选择所属项目',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        }, {
          name: 'CCER价格(元/tCO2e)',
          prop: 'ccerPrice',
          componentType: 'el-input-number',
          attrConfig: {
            placeholder: '请输入CCER价格',
            min: 0,
            style: { width: '100%' },
            options: []
          },
          selectStyle: { width: '180px' }
        }, {
          name: '碳配额价格(元/tCO2e)',
          prop: 'carbonQuotaPrice',
          componentType: 'el-input-number',
          attrConfig: {
            min: 0,
            style: { width: '100%' },
            placeholder: '请输入碳配额价格',
            options: []
          },
          selectStyle: { width: '180px' }
        }, {
          name: '数据时间',
          prop: 'dataTimeRange',
          componentType: 'el-date-picker',
          attrConfig: {
            placeholder: '请选择数据时间',
            type: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            'picker-options': {
              onPick: this.onPick,
              disabledDate: this.disabledRangeDate
            }
          },
          selectStyle: { width: '180px' }
        }

      ]
    }
  },
  computed: {
    rules() {
      return {
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'blur' }],
        ccerPrice: [{ required: true, message: '请输入CCER价格', trigger: 'blur' }],
        carbonQuotaPrice: [{ required: true, message: '请输入碳配额价格', trigger: 'blur' }],
        dataTimeRange: [{ required: true, message: '请选择数据时间', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popConfig: {
      handler(data) {
        if (data.disabled) {
          this.formList.forEach((e) => {
            e.attrConfig.disabled = true
          })
        }
      },
      deep: true,
      immediate: true
    },
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.id)
        if (data.id) {
          this.formList[3].attrConfig.type = 'datetime'
          this.formData.dataTimeRange = data.dataTime
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      if (!params.id) {
        params.dataTimeStart = params.dataTimeRange[0]
        params.dataTimeEnd = params.dataTimeRange[1]
      } else {
        params.dataTimeStart = params.dataTimeRange
      }
      this.submit(params)
    }
  },
  methods: {
    onPick({ maxDate, minDate }) {
      this.pickMinDate = minDate.getTime()
      if (maxDate) {
        this.pickMinDate = ''
      }
    },
    disabledRangeDate(time) {
      if (this.pickMinDate !== '') {
        const day31 = 31 * 24 * 3600 * 1000;
        let maxTime = this.pickMinDate + day31;
        let minTime = this.pickMinDate - day31;
        return time.getTime() > maxTime || time.getTime() < minTime;
      }
      return false;
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.carbonPriceData[this.isAdd ? 'add' : 'update'](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'carbon-price-data-add')
          } else if (res.msg) {
            this.$message({ type: 'error', message: res.msg })
          }
        }
      })
    }
  }
}
</script>
